package cn.dlc.com;

import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Test;

/**
 * @Author: dlc
 * @Date: 2022/1/13 - 15:20
 * 客户端连接
 */
public class Demo01 {

    @Test
    public void testMethod1() throws Exception{
        // 这个已经过时了，7.3.0的时候可以使用
        // starter可以这么用
        // 连接客户端
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));

        // 构建请求
        GetRequest index = new GetRequest("book", "1");

        // 执行
        GetResponse response = client.get(index, RequestOptions.DEFAULT);

        // 获取结果
        System.out.println(response.getId());
        System.out.println(response.getVersion());
        System.out.println(response.getSourceAsString());
    }


    /**
     * 使用 elasticsearch-java依赖的时候，可以通过下面的方式创建连接
     * 以下为官方提供的方式，不太好用。
     * @throws Exception
     */
    @Test
    public void testMethod2() throws Exception{

        // 连接客户端
/*        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();

        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // 注意这个类，不要引入了一个接口
        ElasticsearchClient client = new ElasticsearchClient(transport);*/

        // 执行
        /*GetResponse response = restClient.get(index, RequestOptions.DEFAULT);

        // 获取结果
        System.out.println(response.getId());
        System.out.println(response.getVersion());
        System.out.println(response.getSourceAsString());*/
    }
}
